package com.chutoutian.service.impl;

import com.chutoutian.mapper.CategoryMapper;
import com.chutoutian.po.Category;
import com.chutoutian.po.CategoryProduct;
import com.chutoutian.service.CategoryService;
import com.chutoutian.untils.SnowflakeIdWorker;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;


    public List<Category> findTree() {
        List<Category> result = new ArrayList<>();
        List<Category> list = categoryMapper.selectList(null);
        for (Category item : list) {
            if (StringUtils.isEmpty(item.getParentId())) {
                item.setCategoryList(new ArrayList<>());
                result.add(item);
            }
        }

        for (Category item : result) {
            for (Category childItem : list) {
                if (item.getId().equals(childItem.getParentId())) {
                    item.getCategoryList().add(childItem);
                }
            }
        }
        return result;
    }


    @Override
    public void add(Category category) {
        category.setId(SnowflakeIdWorker.getId());
        category.setCreateTime(new Date());
        categoryMapper.insert(category);
    }

    @Override
    public Category get(String id) {
        return categoryMapper.selectById(id);
    }

    @Override
    public void update(Category category) {
        categoryMapper.updateById(category);
    }

    @Override
    public void delete(String id) {
        categoryMapper.deleteById(id);
    }

    @Override
    public void addCategoryProduct(String categoryId, String productId) {

        CategoryProduct categoryProduct = new CategoryProduct();
        categoryProduct.setId(SnowflakeIdWorker.getId());
        categoryProduct.setCategoryId(categoryId);
        categoryProduct.setProductId(productId);
        categoryMapper.insertCategoryProduct(categoryProduct);

    }
}
